import { Scene } from "three";
import { LoadActors, LoadModel } from "./SceneLoader";
import { Simulate } from "./Simulate";
import { WorkState } from "./Types";
import { ConfigureTool } from "./ConfigureTool";

export function loadAndSimulate(url: string) {
    return new Promise<string>((resolve, reject) => {
      LoadActors(url)
        .then((result) => {
          LoadModel(result.__root as Scene)
            .then(() => {
              console.log('succeed');
              let work = new Simulate(result);
              work.initData();
              let loopLimit = 10000;
              while (work.workState !== WorkState.DONE && loopLimit > 0) {
                work.onUpdate();
                loopLimit--;
                if(loopLimit <= 0) {
                    reject("loop !!!");
                }
              }
              let data = work.exportPipeConnect();
              let test = new ConfigureTool(data);
              test.onInit();
              const jsonString = test.toJson();
              resolve(jsonString);
            })
            .catch((error) => {
              reject(error);
            });
        })
        .catch((error) => {
          reject(error);
        });
    });
  }